Maximize sum of array after k negation [Quick Select]¶
Time: O(N) on average; Space: O(1); easy
Given an array A of integers, we must modify the array in the following way: * we choose an i and replace A[i] with -A[i], and * we repeat this process K times in total.
(We may choose the same index i multiple times.)
Return the largest possible sum of the array after modifying it in this way.
Example 1:
Input: A = [4,2,3], K = 1
Output: 5
Explanation:
Choose indices (1,) and A becomes [4,-2,3].
Example 2:
Input: A = [3,-1,0,2], K = 3
Output: 6
Explanation:
Choose indices (1, 2, 2) and A becomes [3,1,0,2].
Example 3:
Input: A = [2,-3,-1,5,-4], K = 2
Output: 13
Explanation:
Choose indices (1, 4) and A becomes [2,3,-1,5,4].
Notes:
1 <= len(A) <= 10000
1 <= K <= 10000
-100 <= A[i] <= 100
1. Quick select solution¶
[1]:
import random
class Solution1(object):
"""
Time: O(N)~O(N^2), O(N) on average.
Space: O(1)
"""
def largestSumAfterKNegations(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: int
"""
def kthElement(nums, k, compare):
def PartitionAroundPivot(left, right, pivot_idx, nums, compare):
new_pivot_idx = left
nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx]
for i in range(left, right):
if compare(nums[i], nums[right]):
nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]
new_pivot_idx += 1
nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]
return new_pivot_idx
left, right = 0, len(nums) - 1
while left <= right:
pivot_idx = random.randint(left, right)
new_pivot_idx = PartitionAroundPivot(left, right, pivot_idx, nums, compare)
if new_pivot_idx == k:
return
elif new_pivot_idx > k:
right = new_pivot_idx - 1
else: # new_pivot_idx < k.
left = new_pivot_idx + 1
kthElement(A, K, lambda a, b: a < b)
remain = K
for i in range(K):
if A[i] < 0:
A[i] = -A[i]
remain -= 1
return sum(A) - ((remain)%2) * min(A) * 2
[2]:
s = Solution1()
A = [4,2,3]
K = 1
assert s.largestSumAfterKNegations(A, K) == 5
A = [3,-1,0,2]
K = 3
assert s.largestSumAfterKNegations(A, K) == 6
A = [2,-3,-1,5,-4]
K = 2
assert s.largestSumAfterKNegations(A, K) == 13
[3]:
class Solution2(object):
def largestSumAfterKNegations(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: int
"""
A.sort()
remain = K
for i in range(K):
if A[i] >= 0:
break
A[i] = -A[i]
remain -= 1
return sum(A) - (remain % 2) * min(A) * 2
[4]:
s = Solution2()
A = [4,2,3]
K = 1
assert s.largestSumAfterKNegations(A, K) == 5
A = [3,-1,0,2]
K = 3
assert s.largestSumAfterKNegations(A, K) == 6
A = [2,-3,-1,5,-4]
K = 2
assert s.largestSumAfterKNegations(A, K) == 13